<template>
  <md-nav-bar
    :title="data.template_code === 'team' ? (data.pageType === 'leader' ? '队长报名' : '队员报名') : '报名'" />
  <!-- 温馨提示 -->
  <uni-notice-bar v-if="data.warnMsg" :text="data.warnMsg" />
  <view class="container">
    <uni-forms ref="form" :modelValue="data.formData" label-position="top" label-width="100">
      <uni-forms-item label="报名人数" name="sign_num">
        <view class="form-item text-content">
          {{ data.formData?.sign_num }}
        </view>
      </uni-forms-item>

      <!-- 添加报名人按钮 -->
      <!-- <view
        class="add white"
        type="primary"
        @click="handleJumpEnterList"
        style="margin-bottom: 20px"
        v-if="data.pageType === 'member'">
        +添加报名人
      </view> -->

      <!-- 队员报名填入【邀请码】 -->
      <uni-forms-item
        v-if="data.pageType === 'member'"
        label="邀请码"
        name="invite_code"
        :required="data.sign_team_id == -1"
        :rules="[
          {
            required: data.sign_team_id == -1,
            errorMessage: '请输入邀请码',
          },
        ]">
        <uni-easyinput
          v-if="data.sign_team_id == -1"
          type="text"
          v-model="data.formData.invite_code"
          placeholder="请输入邀请码"
          :input-border="false"
          @blur="e => blurText(e, 'invite_code')" />
        <view v-else class="form-item text-content">{{ data.formData.invite_code }}</view>
      </uni-forms-item>

      <!-- 动态表单处理 -->
      <template v-for="item in data.activeFieldList" :key="item.field_name">
        <!-- 【绿色通道】开启的队长【推荐码】 -->
        <uni-forms-item
          v-if="item.field_name === 'refer_code' && data.pageType === 'leader'"
          label="推荐码"
          name="refer_code"
          :required="data.sign_team_id == -1">
          <uni-easyinput
            v-if="data.sign_team_id == -1"
            type="text"
            v-model="data.formData.refer_code"
            placeholder="请输入推荐码"
            :input-border="false" />
          <view v-else class="form-item text-content">{{ data.formData.refer_code }}</view>
        </uni-forms-item>
        <template v-if="item.field_name === 'title'">
          <!-- 针对队员展示 -->
          <!-- 队伍名称 -->
          <uni-forms-item
            label="队伍名称"
            name="title"
            :required="item.is_required == 1"
            :rules="[
              {
                required: item.is_required == 1,
                errorMessage: `请输入${item.field_label}`,
              },
            ]"
            v-if="data.pageType === 'leader'">
            <uni-easyinput
              type="text"
              v-model="data.formData.title"
              placeholder="请输入队伍名称"
              :input-border="false" />
          </uni-forms-item>
          <view v-if="data.pageType !== 'leader' && data.formData?.title" style="margin-bottom: 20px">
            <view class="text-label">队伍名称</view>
            <view class="form-item text-content">{{ data.formData?.title }}</view>
          </view>
        </template>
        <!-- text -->
        <uni-forms-item
          v-if="item.field_type === 'text' && !['invite_code', 'refer_code', 'title'].includes(item.field_name)"
          :label="item.field_label"
          :name="item.field_name"
          :required="item.is_required == 1"
          :rules="[
            {
              required: item.is_required == 1,
              errorMessage: `请输入${item.field_label}`,
            },
          ]">
          <uni-easyinput
            type="text"
            v-model="data.formData[item.field_name]"
            placeholder="请输入"
            :input-border="false" />
        </uni-forms-item>
        <!-- 联系电话 联动 验证码处理 -->
        <uni-forms-item
          v-if="item.field_type === 'text' && item.field_name === 'mobile'"
          label="验证码"
          name="sms_code"
          required
          :rules="[
            {
              required: true,
              errorMessage: '请输入验证码',
            },
          ]">
          <view class="flex-l">
            <uni-easyinput
              type="text"
              v-model="data.formData.sms_code"
              placeholder="请输入验证码"
              :input-border="false" />
            <view class="countdown m-left-20" @click="handleGetCode">
              <text v-show="!data.countdownStatus">获取验证码</text>
              <uni-countdown
                v-if="data.countdownStatus"
                :show-day="false"
                :show-hour="false"
                :show-minute="false"
                :second="data.second"
                :show-colon="false"
                @timeup="timeup" />
            </view>
          </view>
        </uni-forms-item>
        <!-- number -->
        <uni-forms-item
          v-if="item.field_type === 'number'"
          :label="item.field_label"
          :name="item.field_name"
          :required="item.is_required == 1"
          :rules="[
            {
              required: item.is_required == 1,
              errorMessage: `请输入${item.field_label}`,
            },
          ]">
          <uni-easyinput
            type="number"
            v-model="data.formData[item.field_name]"
            placeholder="请输入"
            :input-border="false" />
        </uni-forms-item>
        <!-- select 报名组别 -->
        <template v-if="item.field_name === 'group'">
          <uni-forms-item
            :label="item.field_label"
            :name="item.field_name"
            :required="item.is_required == 1"
            :rules="[
              {
                required: item.is_required == 1,
                errorMessage: `请选择${item.field_label}`,
              },
            ]">
            <view class="form-item" style="padding: 0" v-if="data.pageType === 'leader'">
              <uni-data-select
                v-model="data.formData.group"
                :localdata="data.group_list"
                @change="e => changeSelect(e, 'group')" />
            </view>
            <view v-else class="form-item text-content">{{ data.formData.group_name }}</view>
          </uni-forms-item>
        </template>
        <uni-forms-item
          v-if="item.field_type === 'select' && item.field_name !== 'group'"
          :label="item.field_label"
          :name="item.field_name"
          :required="item.is_required == 1"
          :rules="[
            {
              required: item.is_required == 1,
              errorMessage: `请选择${item.field_label}`,
            },
          ]">
          <view class="form-item" style="padding: 0">
            <view v-if="item.field_name == 'group' && data.pageType !== 'leader'" class="form-item text-content">
              {{ data.formData.group_name }}
            </view>
            <uni-data-select
              v-else
              v-model="data.formData[item.field_name]"
              :localdata="data[item.field_name + '_list']"
              :clear="false" />
          </view>
        </uni-forms-item>
        <!-- radio -->
        <uni-forms-item
          v-if="item.field_type === 'radio'"
          :label="item.field_label"
          :name="item.field_name"
          :required="item.is_required == 1"
          :rules="[
            {
              required: item.is_required == 1,
              errorMessage: `请选择${item.field_label}`,
            },
          ]">
          <template v-slot:label>
            <uni-tooltip
              v-if="['is_houbu', 'is_order_number'].includes(item.field_name)"
              :content="data.fieldTooltip[item.field_name]"
              placement="right">
              <view class="flex-l">
                <text v-if="item.is_required == 1" style="color: red; font-size: 16px">*</text>
                <uni-icons type="info" size="16"></uni-icons>
                <view class="text-label m-left-8">{{ item.field_label }}</view>
              </view>
            </uni-tooltip>
            <view class="text-label m-left-8" v-else>
              <text v-if="item.is_required == 1" style="color: red; font-size: 16px">*</text>
              {{ item.field_label }}
            </view>
          </template>
          <view class="form-item">
            <uni-data-checkbox
              v-model="data.formData[item.field_name]"
              :localdata="
                data[item.field_name.startsWith('is_') ? 'is_list' : item.field_name + '_list']
              "></uni-data-checkbox>
          </view>
        </uni-forms-item>
        <!-- checkbox -->
        <uni-forms-item
          v-if="item.field_type === 'checkbox'"
          :label="item.field_label"
          :name="item.field_name"
          :required="item.is_required == 1"
          :rules="[
            {
              required: item.is_required == 1,
              errorMessage: `请选择${item.field_label}`,
            },
          ]">
          <view class="form-item">
            <uni-data-checkbox
              multiple
              v-model="data.formData[item.field_name]"
              :localdata="[{ text: '', value: 1 }]"></uni-data-checkbox>
          </view>
        </uni-forms-item>
        <!-- 是否预定号码布 特殊处理 -->
        <uni-forms-item
          v-if="item.field_name === 'is_order_number' && data.formData.is_order_number == 1"
          label="自定义号码布"
          name="numbers"
          required
          :rules="[
            {
              required: true,
              errorMessage: `请输入自定义号码布`,
            },
          ]">
          <uni-easyinput type="number" v-model="data.formData.numbers" placeholder="请输入" :input-border="false" />
        </uni-forms-item>
        <!-- date -->
        <uni-forms-item
          v-if="item.field_type === 'date'"
          :label="item.field_label"
          :name="item.field_name"
          :required="item.is_required == 1"
          :rules="[
            {
              required: item.is_required == 1,
              errorMessage: `请选择${item.field_label}`,
            },
          ]">
          <uni-datetime-picker
            type="date"
            :clear-icon="false"
            v-model="data.formData[item.field_name]"
            :border="false" />
        </uni-forms-item>
        <!-- image -->
        <uni-forms-item
          v-if="item.field_type === 'image' && item.field_name != 'back_img'"
          :label="item.field_label"
          :name="item.field_name"
          :required="item.is_required == 1"
          :rules="[
            {
              required: item.is_required == 1,
              errorMessage: `请上传${item.field_label}`,
            },
          ]">
          <view class="form-item">
            <uni-file-picker
              return-type="object"
              limit="1"
              file-mediatype="image"
              :imageStyles="{ width: '200rpx', height: '140rpx' }"
              v-model="data.formData[item.field_name]"
              @select="e => handleUpload(e, item.field_name)">
              <md-icon
                type="bg"
                :name="
                  item.field_name.startsWith('front')
                    ? 'id_front'
                    : item.field_name.startsWith('back')
                    ? 'id_back'
                    : 'mr_front'
                "
                width="200"
                height="140" />
            </uni-file-picker>
          </view>
        </uni-forms-item>
        <uni-forms-item
          v-if="item.field_type === 'image' && item.field_name == 'back_img' && data.formData.id_type == 1"
          :label="item.field_label"
          :name="item.field_name"
          :required="item.is_required == 1"
          :rules="[
            {
              required: item.is_required == 1,
              errorMessage: `请上传${item.field_label}`,
            },
          ]">
          <view class="form-item">
            <uni-file-picker
              return-type="object"
              limit="1"
              file-mediatype="image"
              :imageStyles="{ width: '200rpx', height: '140rpx' }"
              v-model="data.formData[item.field_name]"
              @select="e => handleUpload(e, item.field_name)">
              <md-icon
                type="bg"
                :name="
                  item.field_name.startsWith('front')
                    ? 'id_front'
                    : item.field_name.startsWith('back')
                    ? 'id_back'
                    : 'mr_front'
                "
                width="200"
                height="140" />
            </uni-file-picker>
          </view>
        </uni-forms-item>
      </template>
    </uni-forms>
    <!-- 添加成员 -->
    <view class="card" v-if="groupSelectedRowData?.is_add_member == 1">
      <view class="forms-item-label">
        添加成员{{
          '(小孩' +
          groupSelectedRowData.child_min_age +
          '至' +
          groupSelectedRowData.child_max_age +
          '周岁，老人' +
          groupSelectedRowData.old_min_age +
          '~' +
          groupSelectedRowData.old_max_age +
          '周岁)'
        }}
      </view>
      <view class="form-item-content">
        <view class="member-list">
          <uni-forms ref="memberForm" :modelValue="data.formMemberData" label-position="top" label-width="100">
            <template v-for="wrap in data.memberList" :key="wrap.id">
              <view class="member-item" @click="() => handleToggle(wrap.id)">
                <view class="del-btn">
                  <md-icon name="delete" width="31" height="31" @click="() => del(wrap.id)" />
                </view>
                <view v-for="(field, index) in wrap.fields" :key="field.name">
                  <view class="flex-l">
                    {{ field.value }}
                    <md-icon
                      name="up"
                      width="31"
                      height="31"
                      v-if="index === 0"
                      :style="{
                        transform: !!data.toggleStatus[wrap.id] ? 'rotate(180deg)' : 'none',
                      }" />
                  </view>
                </view>
              </view>
              <view :class="['member-list-form', !!data.toggleStatus[wrap.id] ? 'hide' : '']">
                <template v-for="item in data.activeMemberFieldList" :key="item.field_name">
                  <uni-forms-item
                    v-if="item.field_type !== 'image'"
                    :label="item.field_label"
                    :name="`${wrap.id}.${item.field_name}`"
                    :required="item.is_required == 1"
                    :rules="[
                      {
                        required: item.is_required == 1,
                        errorMessage: `${item.field_label}不能为空`,
                      },
                    ]">
                    <!-- text` -->
                    <uni-easyinput
                      v-if="item.field_type === 'text'"
                      type="text"
                      v-model="data.formMemberData[wrap.id][item.field_name]"
                      placeholder="请输入" />
                    <!-- number -->
                    <uni-easyinput
                      v-if="item.field_type === 'number'"
                      type="number"
                      v-model="data.formMemberData[wrap.id][item.field_name]"
                      placeholder="请输入" />
                    <!-- select -->
                    <view class="form-item" style="padding: 0" v-if="item.field_type === 'select'">
                      <uni-data-select
                        v-model="data.formMemberData[wrap.id][item.field_name]"
                        :localdata="data[item.field_name + '_list']"
                        :clear="false" />
                    </view>
                    <!-- radio -->
                    <view class="form-item" v-if="item.field_type === 'radio'">
                      <uni-data-checkbox
                        v-model="data.formMemberData[wrap.id][item.field_name]"
                        :localdata="
                          data[item.field_name.startsWith('is_') ? 'is_list' : item.field_name + '_list']
                        "></uni-data-checkbox>
                    </view>
                    <!-- checkbox -->
                    <!-- 暂时免责声明 -->
                    <view class="form-item" v-if="item.field_type === 'checkbox'">
                      <uni-data-checkbox
                        multiple
                        v-model="data.formMemberData[wrap.id][item.field_name]"
                        :localdata="[{ text: '', value: 1 }]"></uni-data-checkbox>
                    </view>
                    <!-- date -->
                    <uni-datetime-picker
                      v-if="item.field_type === 'date'"
                      type="date"
                      :clear-icon="false"
                      v-model="data.formMemberData[wrap.id][item.field_name]" />
                  </uni-forms-item>
                  <!-- 是否预定号码布 特殊处理 -->
                  <uni-forms-item
                    v-if="item.field_name === 'is_order_number' && data.formMemberData[wrap.id].is_order_number == 1"
                    label="自定义号码布"
                    :name="`${wrap.id}.numbers`"
                    required
                    :rules="[
                      {
                        required: true,
                        errorMessage: `请输入自定义号码布`,
                      },
                    ]">
                    <uni-easyinput type="number" v-model="data.formMemberData[wrap.id].numbers" placeholder="请输入" />
                  </uni-forms-item>
                  <!-- image -->
                  <uni-forms-item
                    v-if="item.field_type === 'image' && item.field_name != 'back_img'"
                    :label="item.field_label"
                    :name="`${wrap.id}.${item.field_name}`"
                    :required="item.is_required == 1"
                    :rules="[
                      {
                        required: item.is_required == 1,
                        errorMessage: `请上传${item.field_label}`,
                      },
                    ]">
                    <view class="form-item">
                      <uni-file-picker
                        return-type="object"
                        limit="1"
                        file-mediatype="image"
                        :imageStyles="{ width: '200rpx', height: '140rpx' }"
                        v-model="data.formMemberData[wrap.id][item.field_name]"
                        @select="e => handleUpload(e, item.field_name, wrap.id)">
                        <md-icon
                          type="bg"
                          :name="
                            item.field_name.startsWith('front')
                              ? 'id_front'
                              : item.field_name.startsWith('back')
                              ? 'id_back'
                              : 'mr_front'
                          "
                          width="200"
                          height="140" />
                      </uni-file-picker>
                    </view>
                  </uni-forms-item>
                  <uni-forms-item
                    v-if="
                      item.field_type === 'image' &&
                      item.field_name == 'back_img' &&
                      data.formMemberData[wrap.id].id_type == 1
                    "
                    :label="item.field_label"
                    :name="`${wrap.id}.${item.field_name}`"
                    :required="item.is_required == 1"
                    :rules="[
                      {
                        required: item.is_required == 1,
                        errorMessage: `请上传${item.field_label}`,
                      },
                    ]">
                    <view class="form-item">
                      <uni-file-picker
                        return-type="object"
                        limit="1"
                        file-mediatype="image"
                        :imageStyles="{ width: '200rpx', height: '140rpx' }"
                        v-model="data.formMemberData[wrap.id][item.field_name]"
                        @select="e => handleUpload(e, item.field_name, wrap.id)">
                        <md-icon
                          type="bg"
                          :name="
                            item.field_name.startsWith('front')
                              ? 'id_front'
                              : item.field_name.startsWith('back')
                              ? 'id_back'
                              : 'mr_front'
                          "
                          width="200"
                          height="140" />
                      </uni-file-picker>
                    </view>
                  </uni-forms-item>
                </template>
              </view>
            </template>
          </uni-forms>
          <view class="add" type="primary" @click="add">+添加老人或者小孩</view>
        </view>
      </view>
    </view>
    <!-- 提交按钮 -->
    <view class="m-top-40">
      <md-button
        v-if="data.showSubBtn"
        :color="data.configInfo.button_color1 || '#d92121'"
        :text-color="data.configInfo.button_color1_text || '#ffffff'"
        class="submit"
        @click="submit">
        提交
      </md-button>
    </view>
    <!-- 报名须知弹窗 -->
    <RuleDialog ref="rulePopup" :know="data.activeDetailInfo.know" />
  </view>
</template>

<script setup lang="ts">
import { onLoad, onShow } from '@dcloudio/uni-app';
import { reactive, ref } from 'vue';
// 接口
import {
  activeDetail,
  activeGroup,
  check_ocr_identity,
  getActiveField,
  getActiveSizeList,
  getTeamInfo,
  send_sms,
  signTeamLeader,
  signTeamMember,
  uploadImage,
  userSignConfig,
} from '@/api';
import type { Active, SignTeam } from '@/api/data';
// 工具
import { formatSignValue, formatSignSubmitValue } from './util';
import { parseParams, Toast } from '@/utils/util';
import { payOrder } from '@/utils/api';
// 组件
import RuleDialog from '@/pages/activity/components/ruleDialog.vue';
import { fromType } from '@/api/enum';

const data = reactive<any>({
  configInfo: {},
  activeFieldList: [], // 活动字段
  activeMemberFieldList: [], // 附带人员活动字段
  showSubBtn: true,
  active_id: -1,
  sign_team_id: -1, // 队伍id
  pageType: '', // 队长报名（leader） | 队员报名（member）
  formData: {
    title: '',
    truename: '',
    idcard: '',
    sex: 1,
    birth: null,
    id_type: 1,
    age: '',
    group: '',
    sign_num: '',
    size: '',
    mobile: '',
    sms_code: '',
    contact: '',
    contact_mobile: '',
    front_img: {},
    back_img: {},
    refer_code: '',
  },
  formMemberData: {},
  memberList: [], // 成员添加
  sex_list: [
    {
      text: '男',
      value: 1,
    },
    {
      text: '女',
      value: 2,
    },
  ],
  is_list: [
    {
      text: '是',
      value: 1,
    },
    {
      text: '否',
      value: 2,
    },
  ],
  id_type_list: [], // 证件类型下拉
  size_list: [], // 服装尺寸下拉
  group_list: [], // 组别下拉
  teamInfo: {}, // 队伍信息
  signTips: '', // 提交报名提示信息
  countdownStatus: false, // 是否开始倒计时
  second: 0, // 验证码倒计时
  from: '', // 从哪个页面过来的
  fieldTooltip: {
    is_houbu: '参与摇号候补，如摇号时未中签将继续排队，当有队伍退赛时可再次摇号。',
    is_order_number: '自定义号码布需要额外收费',
  },
  toggleStatus: {} as Record<number, boolean>, // 成员展开收起状态
  template_code: '',
  warnMsg: '', // 温馨提示
  activeDetailInfo: {}, // 活动详情信息
});

const form = ref<any>(null);
const memberForm = ref<any>(null);
const isLeader = ref<boolean>(true);
const openType = ref('page');
const groupListData = ref<Active.Group.Data[]>([]); // 组别下拉copy一份
const groupSelectedRowData = ref<Active.Group.Data>(); // 组别下拉copy一份
const rulePopup = ref<any>(null); // 规则弹窗相关

const handleToggle = (id: number) => {
  data.toggleStatus[id] = !data.toggleStatus[id];
  console.log(data.toggleStatus);
};

const setfields = (vals: any) => [
  { label: '姓名', name: 'truename', value: vals?.truename },
  { label: '性别', name: 'sex', value: vals?.sex === 1 ? '男' : '女' },
  { label: '年龄', name: 'age', value: vals?.age ? vals.age + '岁' : '' },
  { label: '电话', name: 'mobile', value: vals?.mobile },
];

// 组别下拉回调
const changeSelect = (value: number, type: string) => {
  if (type === 'group') {
    const item = groupListData.value?.find(item => item.id === value);
    data.formData.group_name = item?.name || '';
    groupSelectedRowData.value = item;
    fetchGetSizeList(value); // 通过组别获取尺码
  }
};

// 点击获取验证码
const handleGetCode = () => {
  if (data.countdownStatus) return;
  if (!data.formData?.mobile) {
    Toast('请填写手机号再进行操作！');
    return;
  }
  fetchSendSms(data.formData?.mobile);
};

// 倒计时结束回调
const timeup = () => {
  data.countdownStatus = false;
};

// 回退页面逻辑
// const cbPage = () => {
//   if (openType.value === 'share') {
//     uni.switchTab({ url: '/pages/index/index' });
//   } else {
//     uni.navigateBack();
//     // 返回的页面执行刷新
//     uni.setStorageSync('isRefresh', 1);
//   }
// };

// 添加携带人员
function add() {
  if (!data.formData?.group) {
    Toast('请选择组别在进行操作！');
    return;
  }
  isLeader.value = false;
  const _checkedList = data.memberList.map((item: { id: number }) => item.id);
  uni.navigateTo({
    url: '/pages/other/registration-management/index?type=multiple&checkedList=' + JSON.stringify(_checkedList),
  });
}

function del(id: number) {
  uni.showModal({
    title: '提示',
    content: '是否删除该成员？',
    success: res => {
      if (res.confirm) {
        let index = data.memberList.findIndex((v: { id: number }) => v.id === id);
        data.memberList.splice(index, 1);
        memberForm.value?.setValue(id, undefined);
        delete data.formMemberData[id];
      }
    },
  });
}

// 触发提交表单
const submit = async () => {
  try {
    const res = await form.value?.validate();
    let memberRes: any = {};
    let ruleValidate = true;
    if (data.memberList.length > 0 && memberForm.value) {
      try {
        memberRes = await memberForm.value.validate();
      } catch (e: any) {
        console.error('成员表单验证失败:', e);
        ruleValidate = false;
        e?.length && Toast(e?.[e?.length - 1]?.errorMessage);
      }
    }

    if (!ruleValidate) return;

    if (
      res.age < (groupSelectedRowData.value?.min_age || 0) ||
      res.age > (groupSelectedRowData.value?.max_age || 1000)
    ) {
      uni.showModal({
        title: '提示',
        content: `报名人年龄需在${groupSelectedRowData.value?.min_age}岁 ~ ${groupSelectedRowData.value?.max_age}岁区间`,
        showCancel: false,
      });
      return;
    }
    // 成员
    const members = (Object.values(memberRes || {}) as SignTeam.Leader.Member[])?.map(item => ({
      ...formatSignSubmitValue(item),
      is_main: '2',
    }));
    uni.showModal({
      title: '提示',
      content: data?.signTips || '是否确认提交报名信息',
      confirmText: '确认提交',
      cancelText: '再修改',
      success: s => {
        if (s.confirm) {
          const obj = formatSignSubmitValue(res);
          if (data.pageType === 'leader') {
            // 【队长报名】
            signTeamLeader({
              active_id: data.active_id,
              title: obj?.title,
              group: obj?.group,
              is_houbu: obj?.is_houbu,
              refer_code: obj?.refer_code,
              members: [{ ...obj, is_main: '1' }, ...members],
            }).then(res => {
              if (res.data.is_charge == 1) {
                payOrder(res.data, type => {
                  const msg = type === 'success' ? '报名费用支付成功' : '用户取消支付';
                  uni.showModal({
                    title: '提示',
                    content: msg,
                    showCancel: false,
                    success: res => {
                      if (res.confirm) {
                        if (type === 'success') {
                          uni.redirectTo({
                            url: '/pages/other/status/pay-success',
                          });
                        } else {
                          // 用户取消支付，停留当前页面
                          uni.switchTab({ url: '/pages/index/index' });
                        }
                      }
                    },
                  });
                });
              } else {
                uni.showModal({
                  title: '提示',
                  content: res?.msg || '报名成功',
                  showCancel: false,
                  success: res => {
                    if (res.confirm) {
                      uni.switchTab({ url: '/pages/index/index' });
                    }
                  },
                });
              }
            });
          } else {
            // 【队员报名】
            // 活动id处理
            const active_id = data?.active_id || data.formData?.active_id;
            //  邀请码处理
            const invite_code = res?.invite_code || data.formData?.invite_code;
            signTeamMember({
              active_id,
              invite_code,
              members: [{ ...obj, is_main: '1' }, ...members],
            }).then(res => {
              if (res.data.is_charge == 1) {
                payOrder(res.data, type => {
                  const msg = type === 'success' ? '报名费用支付成功' : '用户取消支付';
                  uni.showModal({
                    title: '提示',
                    content: msg,
                    showCancel: false,
                    success: res => {
                      if (res.confirm) {
                        // 从分享页跳过来则跳转活动详情页
                        if (data?.from == 'share') {
                          uni.redirectTo({
                            url: '/pages/activity/detail?active_id=' + data.active_id,
                          });
                        } else {
                          if (type === 'success') {
                            uni.redirectTo({
                              url: '/pages/other/status/pay-success',
                            });
                          } else {
                            uni.switchTab({ url: '/pages/index/index' });
                          }
                        }
                      }
                    },
                  });
                });
              } else {
                uni.showModal({
                  title: '提示',
                  content: res?.msg || '报名成功',
                  showCancel: false,
                  success: res => {
                    if (res.confirm) {
                      // 从分享页跳过来则跳转活动详情页
                      if (data?.from == 'share') {
                        uni.redirectTo({
                          url: '/pages/activity/detail?active_id=' + data.active_id,
                        });
                      } else {
                        uni.switchTab({ url: '/pages/index/index' });
                      }
                    }
                  },
                });
              }
            });
          }
        }
      },
    });
  } catch (e) {
    //TODO handle the exception
    console.log('表单错误信息：', e);
    e?.length && Toast(e?.[e?.length - 1]?.errorMessage);
  }
};

// 跳转录入的队员列表选择
const handleJumpEnterList = () => {
  isLeader.value = true;
  uni.navigateTo({
    url: '/pages/other/registration-management/index?type=select',
  });
};

// 邀请码失焦事件
const blurText = (e: any, type: string) => {
  const { value } = e.detail;
  if (type === 'invite_code') {
    fetchGetTeamInfo({ invite_code: value });
  }
};

/**
 * 上传相关
 */
const handleUpload = (e: any, type: string, userId?: number) => {
  let { tempFilePaths } = e;
  uni.showLoading({
    title: '图片上传中...',
    mask: true,
  });
  uploadImage({ filePath: tempFilePaths[0], formData: { category: 'sign', active_id: data.active_id } })
    .then(async res => {
      const obj = {
        url: res.data.url,
        extname: 'png',
        name: type + '.png',
      };
      if (!userId) {
        if ([1, 2, 3, 4, 9].includes(data.formData.id_type) && type === 'front_img') {
          const info = await fetchCheckOcrIdentity(res?.data?.url);
          data.formData = { ...data.formData, ...info };
        }
        data.formData[type] = obj;
      } else {
        // 附带人员
        if ([1, 2, 3, 4, 9].includes(data.formMemberData[userId].id_type) && type === 'front_img') {
          const info = await fetchCheckOcrIdentity(res?.data?.url);
          data.formMemberData[userId] = {
            ...data.formMemberData[userId],
            ...info,
          };
        }
        data.formMemberData[userId][type] = obj;
      }
    })
    .catch(e => {
      data.formData[type] = {};
      userId && (data.formMemberData[userId][type] = {});
    })
    .finally(() => {
      uni.hideLoading();
    });
};

/**
 * 接口相关
 */
// 获取动态表单数据
const fetchGetActiveField = async (active_id: number, type: 'leader' | 'member') => {
  try {
    const res = await getActiveField({ active_id });
    // 队员特殊处理一下,队伍名称和组别
    data.activeFieldList =
      type === 'leader'
        ? res.data || []
        : res.data?.filter(item => item.is_member_show == 1 || ['title', 'group'].includes(item.field_name)) || [];
    // 附带人动态字段处理
    data.activeMemberFieldList = res.data?.filter(item => item.is_member_show == 1) || [];
  } catch (error) {}
};

// 获取其他下拉数据
const fetchUserSignIndex = async () => {
  try {
    const res = await userSignConfig();
    for (let [key, value] of Object.entries(res.data)) {
      if (key !== 'sign_tips') {
        data[key + '_list'] = value || [];
      } else {
        data.signTips = res.data.sign_tips;
      }
    }
    return true;
  } catch (error) {}
  return false;
};

// 根据组别获取尺码
const fetchGetSizeList = async (group_id: number) => {
  try {
    const res = await getActiveSizeList({ group_id });
    data.size_id_list =
      res.data?.map(item => ({
        text: `${item.name}（库存：${item.rest_inventory}）`,
        value: item.id,
      })) || [];
  } catch (error) {}
};

// 获取组别下拉
const fetchActiveGroup = async (active_id: number) => {
  if (!active_id) return;
  try {
    const res = await activeGroup({ active_id });
    data.group_list = res.data.map(item => ({
      text: item.name,
      value: item.id,
    }));
    groupListData.value = res.data;
    return true;
  } catch (e) {
    //TODO handle the exception
  }
  return false;
};

// 校验身份证图片
const fetchCheckOcrIdentity = async (front_img: string) => {
  try {
    const res = await check_ocr_identity({
      front_img,
      id_type: data.formData.id_type,
    });
    return res.data;
  } catch (error) {}
  return undefined;
};

// 查询队伍信息
const fetchGetTeamInfo = async (params: Partial<SignTeam.Info.Query>) => {
  if (!params.invite_code && params.sign_team_id == -1) return;
  try {
    const res = await getTeamInfo(params);
    data.showSubBtn = true;
    data.formData = { ...data.formData, ...res.data };
    const item = groupListData.value?.find(item => item.id === res.data?.group);
    groupSelectedRowData.value = item;
    fetchGetSizeList(res.data.group);
  } catch (error: any) {
    data.showSubBtn = false;
    const _msg = error?.msg || '队伍不存在或组队成功';
    uni.showModal({
      title: '提示',
      content: _msg,
      showCancel: false,
    });
    data.warnMsg = _msg;
  }
};

// 手机获取验证码
const fetchSendSms = async (mobile: string) => {
  try {
    const res = await send_sms({
      mobile,
      event: data.pageType === 'leader' ? 'header_sign ' : 'member_sign',
    });
    Toast(res?.msg || '发送成功');
    data.countdownStatus = true;
    data.second = 59;
  } catch (error) {}
};

// 活动详情
const fetchActiveDetail = async (active_id: number) => {
  try {
    const res = await activeDetail({
      active_id,
    });
    data.activeDetailInfo = res.data;
    rulePopup.value?.open?.();
  } catch (error) {}
};

onLoad(option => {
  const configInfo = uni.getStorageSync('configInfo') ? JSON.parse(uni.getStorageSync('configInfo')) : '';
  if (configInfo) {
    data.configInfo = configInfo;
  }
  const params = parseParams(option?.params);
  data.active_id = params?.active_id;
  data.pageType = params?.type;
  data.formData.sign_num = params?.sign_num; // 处理报名数量
  data.sign_team_id = params?.sign_team_id || -1;
  data.formData.invite_code = params?.invite_code;
  data.from = params?.from; // 从哪里跳转过来的 share | defalut(默认不传)
  data.template_code = params?.template_code; // 从哪里跳转过来的 share | defalut(默认不传)

  // 是否候补相关处理
  if (params?.is_houbu == '1') {
    data.is_houbu = params?.is_houbu;
    data.formData.is_houbu = 2;
  }

  // 通过什么方式打开的页面 page | share
  openType.value = params?.openType || 'page';
  // 接口调用
  uni.showLoading({
    title: '加载中',
  });
  Promise.all([
    fetchGetActiveField(params?.active_id, params?.type),
    fetchUserSignIndex(),
    fetchActiveGroup(params?.active_id),
    fetchGetTeamInfo({
      sign_team_id: params?.sign_team_id || -1,
      invite_code: params?.invite_code || '',
    }),
  ]).finally(() => {
    uni.hideLoading();
  });

  // 除了【活动详情】页跳转过来都会弹报名须知弹窗
  if (params?.from !== fromType.活动详情) {
    fetchActiveDetail(params?.active_id);
  }
});

onShow(() => {
  const selectUser = uni.getStorageSync('selectUser');
  if (selectUser) {
    const _selectUser = JSON.parse(selectUser);
    if (isLeader.value) {
      // 添加报名人，【单选】的处理
      data.formData = formatSignValue({
        ...data.formData,
        ..._selectUser?.[0],
        sign_num: data.formData?.sign_num,
      });
    } else {
      // 选择老人和小孩，【多选】的处理
      let _memberList: any[] = [];
      _selectUser.forEach((item: any) => {
        const userId = item?.id || Date.now();
        _memberList.push({
          fields: setfields(item),
          id: userId,
        });
        // 确保formMemberData对象已初始化
        if (!data.formMemberData[userId]) {
          data.formMemberData[userId] = {};
        }
        data.formMemberData[userId] = formatSignValue(item);
      });
      data.memberList = _memberList;
    }
    uni.removeStorageSync('selectUser');
  }

  // 登录跳转过来执行
  if (uni.getStorageSync('isRefresh')) {
    uni.removeStorageSync('isRefresh');
    // 接口调用
    uni.showLoading({
      title: '加载中',
    });
    Promise.all([
      fetchGetActiveField(data?.active_id, data.pageType),
      fetchUserSignIndex(),
      fetchActiveGroup(data?.active_id),
      fetchGetTeamInfo({
        sign_team_id: data?.sign_team_id || -1,
        invite_code: data?.invite_code || '',
      }),
    ]).finally(() => {
      uni.hideLoading();
    });
  }
});
</script>

<style lang="scss" scoped>
.container {
  padding: 30rpx;
  .forms-item-label {
    height: 36px;
    line-height: 36px;
    padding-bottom: 10px;
    font-size: 14px;
    color: #606266;
  }
  .text-label {
    height: 28px;
    line-height: 28px;
    font-size: 14px;
    color: #606266;
    padding-bottom: 8px;
    box-sizing: border-box;
  }
  .form-item {
    background: white;
    border-radius: 10rpx;
    padding: 10rpx 0 10rpx 10px;
    &.text-content {
      height: 30px;
      line-height: 30px;
      font-size: 14px;
    }
  }
  .form-item-content {
    padding: 16rpx;
    background: white;
  }
  .form-item-row {
    position: relative;
    .del-button {
      position: absolute;
      right: 0;
      top: 0;
    }
  }
  .member-list {
    .del-btn {
      position: absolute;
      top: 0;
      right: 0;
    }
    .up-btn {
      position: absolute;
      top: 50%;
      left: 0;
    }
    .member-item {
      position: relative;
      width: 100%;
      height: 80rpx;
      background: #f7f7f7;
      border-radius: 10rpx;
      font-size: 28rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 24rpx;
      box-sizing: border-box;
      margin-bottom: 20rpx;
    }
  }
  .member-list-form {
    opacity: 1;
    height: auto;
    &.hide {
      opacity: 0;
      height: 0;
    }
    .form-item {
      border: 1px solid #e5e5e5;
    }
    .uni-drawer .uni-scroll-view {
      -webkit-overflow-scrolling: auto;
    }
  }
  .add {
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    background: #f7f7f7;
    border-radius: 10rpx;
    color: #b3b3b3;
    font-size: 28rpx;
    text-align: center;
    &.white {
      background: white;
      color: $title;
    }
  }

  .countdown {
    height: 35px;
    padding: 0 20px;
    border: 1px solid $lineColor;
    line-height: 35px;
    border-radius: 8rpx;
    box-sizing: border-box;
  }
}
</style>
